<template>
  <BasicDialog ref="tenantMenuDialog" :isVisible="isAlert"   width="30%" :title="title" @handleSure="handleSure">
    <template #content>
      <el-form ref="formRef" :model="formInfo" :rules="rules" label-width="120px">
        <el-form-item label="菜单权限：" prop="menuIds">
          <el-cascader ref="cascaderRef" :options="menuObj.menusTree" :props="menuObj.props"
            placeholder="请选择菜单权限" v-model="formInfo.menuIds" collapse-tags collapse-tags-tooltip max-collapse-tags="7"
            clearable ></el-cascader>
        </el-form-item>
      </el-form>
    </template>
  </BasicDialog>
</template>
<script lang='ts' setup>
import { FormInfo } from "@components/common/BasicForm/BasicFormTypes";
import type { FormInstance, FormRules } from 'element-plus';
import { toTreeData } from "@/utils";
import { tenantGetMenu, tenantAssignMenu } from "@/request/apis/system/tenant";
import { getActiontreeTree } from "@/request/apis/system/menu";

const props = defineProps({
  info: {
    type: Object,
    default: () => {
      return {}
    }
  },
  isAlert: {
    type: Boolean,
    default: false
  },
  parentData: {
    type: Object,
    default: () => {
      return {}
    }
  }
})

const $emits = defineEmits([
  "closeDialog"
])

//表单数据 
let formInfo = ref<FormInfo>({});

const cascaderRef = ref()
let menuObj = reactive<FormInfo>({
  menusTree: [],  // 展示菜单选择的层级数据
  props: {
    //菜单权限的选择属性
    multiple: true,
    expandTrigger: "click",
    value: "id",
    label: "mname",
    emitPath: false
  },
  menuHalf: new Set(),  // 半选的菜单
})

// 表单校验规则
const rules = reactive<FormRules>({
})

// 提交表单校验
const formRef = ref<FormInstance>();
const tenantMenuDialog = ref();

// 用来处理菜单选择的数据处理
function getHalfMenus() {
  menuObj.menuHalf.clear()
  const checkedNodes = cascaderRef.value.getCheckedNodes(true)
  checkedNodes.forEach((node:any) => {
    let len = node.pathValues.length
    for(let i = 0; i < len-1; i++){
      menuObj.menuHalf.add(node.pathValues[i]);
    }
  });
}
async function handleSure() {
  formRef.value.validate(valid => {
    if (valid) {
      tenantMenuDialog.value.changeLoading(true);
      getHalfMenus()
      let params = {
        ...formInfo.value,
        halfMenuIds: [...menuObj.menuHalf],
      }
      let funName = tenantAssignMenu
      funName(params).then((res: any) => {
        ElMessage.success("操作成功")
        tenantMenuDialog.value.changeLoading(false);
        $emits("closeDialog", 0);
      }).catch(err => {
        tenantMenuDialog.value.changeLoading(false);
      })

    } 
  })
}

const title = ref("");
onMounted(async() => {
  title.value = '修改'
  const data = await tenantGetMenu(props.info.id)
  formInfo.value = data 
  // 获取菜单数据
  const menus = await getActiontreeTree({hasButton:true})
  menuObj.menusTree = toTreeData(menus,"pid","id");
})

</script>

<style scoped lang="scss"></style>